<!--
 * @Author: your name
 * @Date: 2022-11-14 14:38:16
 * @LastEditTime: 2022-11-16 16:27:09
 * @LastEditors: yuhan
 * @Description: 
 * @FilePath: \apiadmin\src\components\CustomBreadcrumb\index.vue
-->
<template>
  <div class="custom-breadcrumb">
    <div class="btnList">
      <el-button v-if="breadcrumbList.length > 1" :icon="Back" circle @click="routerBack" />
    </div>
    <!-- <el-breadcrumb class="breadcrumb" separator="/">
      <el-breadcrumb-item v-for="breadcrumbItem in breadcrumbList" :key="breadcrumbItem.path">{{
        breadcrumbItem.name
      }}</el-breadcrumb-item>
    </el-breadcrumb> -->
  </div>
</template>
<script setup>
import { Back } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { computed, onMounted, watch } from "vue";
import { useStore } from "vuex";
const router = useRouter();
const store = useStore();
const getPath = (data) => {
  let returnPath = data.path;
  let returnQuery = "";
  let paramObj = data.param;
  if (paramObj) {
    for (let key in paramObj) {
      returnQuery += `${key}=${paramObj[key]}&`;
    }
  }
  return returnQuery
    ? `${returnPath}?${returnQuery.substr(0, returnQuery.length - 1)}`
    : returnPath;
};
const breadcrumbList = computed(() => {
  let formatNreadcrumbList = store.getters["customBreadcrumb/breadcrumbList"].map((item, index) => {
    return {
      ...item,
      fullPath: getPath(item),
    };
  });
  return formatNreadcrumbList;
});

const routerBack = () => {
  store.dispatch("customBreadcrumb/deleteBreadcrumb", router.currentRoute.value.path);
  router.back();
};
watch(
  () => router,
  (nv) => {
    let curRouter = nv.currentRoute.value;
    let targetIndex = breadcrumbList.value.findIndex((it) => it.path === curRouter.path);

    // 当前页面不存在面包屑列表的时候要加进面包屑
    if (targetIndex === -1) {
      const query = {
        path: curRouter.path,
        name: curRouter.meta.title,
        param: curRouter.query,
      };
      store.dispatch("customBreadcrumb/setBreadcrumb", query);
    } else {
      // 当前页面存在面包屑列表的时候需要判断是否要删除上个面包屑
      if (curRouter.path === breadcrumbList.value[0].path) {
        store.dispatch("customBreadcrumb/initBreadcrumb");
      }
    }
  },
  { immediate: true, deep: true }
);
</script>
<style lang="scss" scoped>
.custom-breadcrumb {
  padding: 10px 20px;
  padding-left: 0;
  display: flex;
  // justify-content: space-between;
  .btnList {
    margin: 0 10px;
  }
  .breadcrumb {
    line-height: 32px;
  }
}
</style>
